/*
 * Copyright 1999-2101 Alibaba Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.fastjson.serializer;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * 
 * @author wenshao<szujobs@hotmail.com>
 * 
 */
public class DateSerializer extends ObjectSerializer {
	public final static DateSerializer instance = new DateSerializer();

	@Override
	public void write(JSONSerializer serializer, Object object) throws IOException {
		SerializeWriter out = serializer.getWrier();
		
		Date date = (Date) object;
		long time = date.getTime();
		if (serializer.isEnabled(SerializerFeature.UseISO8601DateFormat)) {
			if (serializer.isEnabled(SerializerFeature.UseSingleQuotes)) {
				out.append('\'');
			} else {
				out.append('\"');
			}
			
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(time);

			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH) + 1;
			int day = calendar.get(Calendar.DAY_OF_MONTH);
			int hour = calendar.get(Calendar.HOUR_OF_DAY);
			int minute = calendar.get(Calendar.MINUTE);
			int second = calendar.get(Calendar.SECOND);
			int millis = calendar.get(Calendar.MILLISECOND);

			char[] buf;
			if (millis != 0) {
				buf = "0000-00-00T00:00:00.000".toCharArray();
				IOUtils.getChars(millis, 23, buf);
				IOUtils.getChars(second, 19, buf);
				IOUtils.getChars(minute, 16, buf);
				IOUtils.getChars(hour, 13, buf);
				IOUtils.getChars(day, 10, buf);
				IOUtils.getChars(month, 7, buf);
				IOUtils.getChars(year, 4, buf);

			} else {
				if (second == 0 && minute == 0 && hour == 0) {
					buf = "0000-00-00".toCharArray();
					IOUtils.getChars(day, 10, buf);
					IOUtils.getChars(month, 7, buf);
					IOUtils.getChars(year, 4, buf);
				} else {
					buf = "0000-00-00T00:00:00".toCharArray();
					IOUtils.getChars(second, 19, buf);
					IOUtils.getChars(minute, 16, buf);
					IOUtils.getChars(hour, 13, buf);
					IOUtils.getChars(day, 10, buf);
					IOUtils.getChars(month, 7, buf);
					IOUtils.getChars(year, 4, buf);
				}
			}

			out.write(buf);
			
			if (serializer.isEnabled(SerializerFeature.UseSingleQuotes)) {
				out.append('\'');
			} else {
				out.append('\"');
			}
		} else {
			out.writeLong(time);
		}
	}
}